/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cci;

import cdp.Cliente;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author CDIG01
 */
@WebServlet(name = "CtrlAdmin", urlPatterns = {"/admin"})
public class CtrlAdmin extends Ctrl {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        view = "/admin/login_formulario.jsp";

        if (view != null) {
            redirecionar(request, response);
            return;
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String evento = request.getParameter("evento");

        if (evento != null) {
            if (evento.equals("logout")) {
                request.getSession().invalidate();
                url = "/admin";
                processRequest(request, response);
                return;
            }
        }
        
        if(request.getSession().getAttribute("admin") != null) {
            view = "/admin/admin_menu.jsp";
            redirecionar(request, response);
            return;
        }

        if (view != null) {
            redirecionar(request, response);
            return;
        }
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String evento = request.getParameter("evento");

        if (evento != null) {
            if (evento.equals("logar")) {
                try {
                    String login = request.getParameter("login");
                    String senha = request.getParameter("senha");

                    if (login.equals("admin") && senha.equals("admin")) {
                        HttpSession session = request.getSession();
                        session.setAttribute("admin", login);
                    } else {
                        mensagem = "Login ou senha invalidos";
                    }
                } catch (Exception e) {
                    mensagem = "Erro ao logar";
                }
                url = "/admin";
            }
        }

        if (view != null) {
            redirecionar(request, response);
            return;
        }
        processRequest(request, response);
    }
}
